package monster.com.cvh.receiver;

/**
 * @author: ASUS
 * @data: 2018/3/30
 * @function:
 */

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;
import monster.com.cvh.activity.CommentDetailsActivity;
import monster.com.cvh.activity.MessageNoticeActivity;
import monster.com.cvh.activity.ResumeTemplateShopActivity;
import monster.com.cvh.bean.GetCommentInfoBean;
import monster.com.cvh.bean.PushPraiseBean;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.util.TimeConvert;
import monster.com.cvh.util.TimeUtil;
import monster.com.cvh.util.ToastUtils;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 自定义接收器
 *
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    private static StringBuilder sb;
    private String type;
    private JSONObject info;
    private String string;

    @Override
    public void onReceive(final Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            string = bundle.getString(JPushInterface.EXTRA_EXTRA);
        }
        if (string != null) {
            try {
                JSONObject jsonObject = new JSONObject(string);
                info = jsonObject.getJSONObject("info");
                type = (String) info.get("type");
                switch (type){
                    case "comment":
                        //收到评论显示
                        SPUtils.putBoolean(context,"showComment",true);
                        break;
                    case "praise":
                        //收到赞，显示赞
                        SPUtils.putBoolean(context,"showPraise",true);
                        break;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = null;
            if (bundle != null) {
                regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                SPUtils.putString(context,"pushId",regId);
            }
            Log.d(TAG, " pushid : " + regId);
            //send the Registration Id to your server...
//            SPUtils.putString();
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            processCustomMessage(context, bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
                switch (type){
                    case "comment":
                        SPUtils.putBoolean(context,"showComment",false);
                        try {
                            JSONObject comment_info = info.getJSONObject("comment_info");
                            int id = (int) comment_info.get("lv1_comment_id");
                            Log.i(TAG, "我是id: "+id);
//                        评论的推送
//                        PushCommentBean pushCommentBean = gson.fromJson(string, PushCommentBean.class);
                            toCommentDetails(context,id);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        break;
                    case "praise":
                        //点赞
                        SPUtils.putBoolean(context,"showPraise",false);
                        Gson gson = new Gson();
                        PushPraiseBean pushPraiseBean = gson.fromJson(string, PushPraiseBean.class);
                        int lv1_comment_id = pushPraiseBean.getInfo().getComment_info().getLv1_comment_id();
                        int comment_id = pushPraiseBean.getInfo().getComment_info().getComment_id();
                        Log.i(TAG, "lv1_comment_id: "+lv1_comment_id+"comment_id:"+comment_id);
                        if (String.valueOf(lv1_comment_id).equals("0")){
                            toCommentDetails(context,comment_id);
                        }else {
                            toCommentDetails(context,lv1_comment_id);
                        }

                        break;
                    case "notice":
                        //系统通知普通消息
                        toNotice(context);
                        break;
                    case "article":
                        //系统推送文章
                        toNotice(context);
                        break;
                    case "template_release":
                        //推送新模板
                        Intent intentResumeTemplate = new Intent(context, ResumeTemplateShopActivity.class);
                        intentResumeTemplate.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intentResumeTemplate);
                        break;
                }



        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
        } else {
            Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    private void toNotice(Context context) {
        Intent intent = new Intent(context, MessageNoticeActivity.class);
        intent.putExtra("id",2);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 跳转新闻详情页面
     * @param context 上下文
     * @param commentId 评论id
     */
    private void toCommentDetails(final Context context, int commentId) {

        OkGo.<String>get(MyConstant.GET_COMMENT_INFO).params("token",SPUtils.getString(context,"token",""))
                .params("comment_id",commentId).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Gson gson = new Gson();
                GetCommentInfoBean getCommentInfoBean = gson.fromJson(s, GetCommentInfoBean.class);
                switch (getCommentInfoBean.getCode()){
                    case 1:
                        GetCommentInfoBean.DataBean data = getCommentInfoBean.getData();
                        Intent intent = new Intent(context, CommentDetailsActivity.class);
                        intent.putExtra("identify",3);
                        intent.putExtra("item", data);
                        long timeStamp = System.currentTimeMillis() / 1000;
                        try {
                            String sTime = TimeConvert.dateToStamp(data.getPublish_time());
                            long articleTime = timeStamp - Long.valueOf(sTime) / 1000;
                            String lastTime = TimeUtil.calculateTime(articleTime);
                            intent.putExtra("time",lastTime);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                        break;
                    case -1006:
                        ToastUtils.showToastLong("此条评论已被删除");
                        break;
                }

            }
        });
    }


    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            }else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it =  json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", 我是内容: [" +
                                myKey + " - " +json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {

    }
}